<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Nibbles in Ruby Qt</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, Nibbles, Qt, Ruby, Game, programming, Linux">
<meta name="description" content="In this chapter of the Ruby Qt tutorial, we will
create a simple Nibbles game clone.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Nibbles</h1>

<p>
In this part of the Ruby Qt programming tutorial, we will create a Nibbles game clone.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
<b>Nibbles</b> is an older classic video game. It was first created in late 70s.
Later it was brought to PCs. In this game the player controls a snake.
The objective is to eat as many apples as possible. Each time the snake eats an apple,
its body grows. The snake must avoid the walls and its own body. 
</p>


<h2>Development</h2>

<p>
The size of each of the joints of a snake is 10px. The snake is controlled with 
the cursor keys. Initially, the snake has three joints. The game starts immediately. 
When the game is finished, we display "Game Over" message in the center of the window.
</p>

<div class="codehead">Board.rb</div>
<pre class="code">
WIDTH = 300
HEIGHT = 300
DOT_SIZE = 10
ALL_DOTS = WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE)
RAND_POS = 29
DELAY = 140

$x = [0] * ALL_DOTS
$y = [0] * ALL_DOTS

class Board &lt; Qt::Widget

    
    def initialize(parent)
        super(parent)
        
        setFocusPolicy Qt::StrongFocus
       
        initGame
    end


    def initGame
    
        @left = false
        @right = true
        @up = false
        @down = false
        @inGame = true
        @dots = 3
        
        begin
            @ball = Qt::Image.new "dot.png"
            @apple = Qt::Image.new "apple.png"
            @head = Qt::Image.new "head.png"
        rescue
            puts "cannot load images"
        end

        for i in (0..@dots)
            $x[i] = 50 - i * 10
            $y[i] = 50
        end

        locateApple
        setStyleSheet "QWidget { background-color: #000000 }"
        
        @timer = Qt::BasicTimer.new 
        @timer.start(140, self)
        
    end


    def paintEvent event

        painter = Qt::Painter.new
        painter.begin self

        if @inGame
            drawObjects painter
        else 
            gameOver painter
        end

        painter.end
    end

    def drawObjects painter

        painter.drawImage @apple_x, @apple_y, @apple

        for z in (0..@dots)
            if z == 0
                painter.drawImage $x[z], $y[z], @head
            else 
                painter.drawImage $x[z], $y[z], @ball
            end
        end
    end

    def gameOver painter
        msg = "Game Over"
        small = Qt::Font.new "Helvetica", 12,
            Qt::Font::Bold.value
        
        metr = Qt::FontMetrics.new small
        
        textWidth = metr.width msg
        h = height
        w = width

        painter.setPen Qt::Color.new Qt::white
        painter.setFont small
        painter.translate Qt::Point.new w/2, h/2
        painter.drawText -textWidth/2, 0, msg
    end


    def checkApple

        if $x[0] == @apple_x and $y[0] == @apple_y 
            @dots = @dots + 1
            locateApple
        end
    end
    
    def move

        z = @dots

        while z > 0
            $x[z] = $x[(z - 1)]
            $y[z] = $y[(z - 1)]
            z = z - 1
        end

        if @left
            $x[0] -= DOT_SIZE
        end

        if @right 
            $x[0] += DOT_SIZE
        end

        if @up
            $y[0] -= DOT_SIZE
        end

        if @down
            $y[0] += DOT_SIZE
        end
        
     end


    def checkCollision

        z = @dots
       
        while z > 0
            if z > 4 and $x[0] == $x[z] and $y[0] == $y[z]
                @inGame = false
            end
            z = z - 1
        end

        if $y[0] > HEIGHT
            @inGame = false
        end
        
        if $y[0] < 0
            @inGame = false
        end
        
        if $x[0] > WIDTH
            @inGame = false
        end
        
        if $x[0] < 0
            @inGame = false
        end    
        
    end


    def locateApple
    
        r = rand RAND_POS
        @apple_x = r * DOT_SIZE
        r = rand RAND_POS
        @apple_y = r * DOT_SIZE
    end

    def timerEvent event

        if @inGame 
            checkApple
            checkCollision
            move
        else 
            @timer.stop
        end

        repaint
    end

    def keyPressEvent event
        
        key = event.key
        
        if key == Qt::Key_Left.value and not @right
            @left = true
            @up = false
            @down = false
        end
        
        if key == Qt::Key_Right.value and not @left
            @right = true
            @up = false
            @down = false
        end
        
        if key == Qt::Key_Up.value and not @down
            @up = true
            @right = false
            @left = false            
        end
        
        if key == Qt::Key_Down.value and not @up
            @down = true
            @right = false
            @left = false
        end
    end
end
</pre>

<p>
First we will define some constants used in our game. 
</p>

<p>
The <code>WIDTH</code> and <code>HEIGHT</code> constants determine 
the size of the Board. The <code>DOT_SIZE</code> is the size of the apple and the dot
of the snake. The <code>ALL_DOTS</code> constant defines the maximum number of 
possible dots on the Board.
The <code>RAND_POS</code> constant is used to calculate a random position of an apple. 
The <code>DELAY</code> constant determines the speed of the game.
</p>

<pre class="explanation">
$x = [0] * ALL_DOTS
$y = [0] * ALL_DOTS
</pre>

<p>
These two arrays store x, y coordinates of all possible joints of a snake. 
</p>

<p>
The <code>initGame</code> method initializes variables, loads 
images and starts a timeout function.
</p>

<pre class="explanation">
if @inGame
    drawObjects painter
else 
    gameOver painter
end
</pre>

<p>
Inside the <code>paintEvent</code> method, we check the 
<code>@inGame</code> variable. If it is true, we draw our objects. 
The apple and the snake joints. Otherwise we display "Game over" text.  
</p>

<pre class="explanation">
def drawObjects painter

    painter.drawImage @apple_x, @apple_y, @apple

    for z in (0..@dots)
        if z == 0
            painter.drawImage $x[z], $y[z], @head
        else 
            painter.drawImage $x[z], $y[z], @ball
        end
    end
end
</pre>

<p>
The <code>drawObjects</code> method draws the apple and the joints of the
snake. The first joint of a snake is its head, which is represented by a red circle. 
</p>

<pre class="explanation">
 def checkApple

     if $x[0] == @apple_x and $y[0] == @apple_y 
         @dots = @dots + 1
         locateApple
     end
 end
</pre>

<p>
The <code>checkApple</code> method checks, if the snake has hit
the apple object. If so, we add another snake joint and call the 
<code>locateApple</code> method, which randomly places a new apple object. 
</p>

<p>
In the <code>move</code> method we have the key algorithm of the game. 
To understand it, look at how the snake is moving. You control the head of the snake. 
You can change its direction with the cursor keys. The rest of the joints move
one position up the chain. The second joint moves where the first was, 
the third joint where the second was etc. 
</p>

<pre class="explanation">
while z > 0
    $x[z] = $x[(z - 1)]
    $y[z] = $y[(z - 1)]
    z = z - 1
end
</pre>

<p>
This code moves the joints up the chain. 
</p>

<pre class="explanation">
if @left
    $x[0] -= DOT_SIZE
end
</pre>

<p>
Move the head to the left.
</p>

<p>
In the <code>checkCollision</code> method, we determine if the snake
has hit itself or one of the walls. 
</p>


<pre class="explanation">
while z > 0
    if z > 4 and $x[0] == $x[z] and $y[0] == $y[z]
        @inGame = false
    end
    z = z - 1
end
</pre>

<p>
Finish the game, if the snake hits one of its joints with the head.
</p>

<pre class="explanation">
if $y[0] > HEIGHT
    @inGame = false
end
</pre>

<p>
Finish the game, if the snake hits the bottom of the Board. 
</p>

<p>
The <code>locateApple</code> method locates an apple randomly 
on the board.
</p>

<pre class="explanation">
r = rand RAND_POS
</pre>

<p>
We get a random number from 0 to RAND_POS - 1. 
</p>

<pre class="explanation">
@apple_x = r * DOT_SIZE
...
@apple_y = r * DOT_SIZE
</pre>

<p>
These line set the x, y coordinates of the apple
object. 
</p>

<pre class="explanation">
if @inGame 
    checkApple
    checkCollision
    move
else 
    @timer.stop
end
</pre>

<p>
Every 140 ms, the <code>timerEvent</code> method is called. If 
we are in the game, we call three methods, that build the logic of the game.
Otherwise we stop the timer. 
</p>


<p>
In the <code>keyPressEvent</code> method of the Board class, we 
determine the keys that were pressed.
</p>

<pre class="explanation">
if key == Qt::Key_Left.value and not @right
    @left = true
    @up = false
    @down = false
end
</pre>

<p>
If we hit the left cursor key, we set <code>@left</code> variable to 
true. This variable is used in the <code>move</code>
method to change coordinates of the snake object. Notice also, that
when the snake is heading to the right, we cannot turn immediately 
to the left. 
</p>

<div class="codehead">Nibbles.rb</div>
<pre class="code">
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, we create
# a Nibbles game clone.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'
require 'Board'

class QtApp &lt; Qt::MainWindow
    
    def initialize
        super
        
        setWindowTitle "Nibbles"
       
        setCentralWidget Board.new(self)
       
        resize 310, 310
        move 300, 300

        show
    end
       
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
</pre>

<p>
In the Nibbles.rb file, we set up the Nibbles game. 
</p>

<img src="/img/gui/qtruby/nibbles.png" alt="Nibbles">
<div class="figure">Figure: Nibbles</div>


<p>
This was the Nibbles computer game programmed with the Qt library and 
the Ruby programming language.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 27, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

